package com.zmx.patients.view.activity;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.EvaluationAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.Doctor;
import com.zmx.patients.pojo.Evaluation;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;
import com.zmx.patients.view.util.ViewStar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 医生详情
 */

public class DoctorDetailsActivity extends BaseActivity {

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.profile_image)
    CircleImageView profileImage;
    @BindView(R.id.department)
    TextView department;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.expertise)
    TextView expertise;
    @BindView(R.id.members_number)
    TextView members_number;
    @BindView(R.id.text_hint)
    TextView text_hint;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.quiz)
    Button quiz;
    @BindView(R.id.focus_on)
    Button focus_on;
    @BindView(R.id.my_team)
    Button my_team;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String did, hosp_id, class_id;//医生id
    private Doctor doctor = null;
    private int asktype = 0;//问诊类型

    private List<Evaluation> lists;
    private EvaluationAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_doctor_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        did = getIntent().getStringExtra("doctor_id");
        class_id = getIntent().getStringExtra("class_id");
        hosp_id = getIntent().getStringExtra("hosp_id");

        lists = new ArrayList<>();
        adapter = new EvaluationAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(adapter);


        getDoctor();

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        JSONObject data = jsonObject.getJSONObject("data");
                        Gson g = new Gson();

                        doctor = g.fromJson(data.toString(), Doctor.class);

                        getComment();
                        initView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 2:

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());

                        if (jsonObject.getInt("code") == 1){

                            JSONArray data = jsonObject.getJSONArray("data");
                            Gson g = new Gson();

                            for (int i = 0;i<data.length();i++){

                                Evaluation evaluation = g.fromJson(data.getJSONObject(i).toString(), Evaluation.class);
                                lists.add(evaluation);

                            }

                            if (lists.size() < 1){
                                text_hint.setVisibility(View.VISIBLE);
                            }

                            adapter.setListAndNotifyDataSetChanged(lists);
                        }else{
                            text_hint.setVisibility(View.VISIBLE);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

//                {"code":1,"msg":"您已成功关注","data":true}

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1){

                            if (object.getString("msg").equals("您已成功关注")){

                                focus_on.setText("取消关注");

                            }else{

                                focus_on.setText("关注他");

                            }


                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    public void initView() {

        name.setText(doctor.getName());
        title.setText(doctor.getTitle_name());
        expertise.setText(doctor.getExpertise());
        department.setText(doctor.getHosp_name() + " " + doctor.getClass_name());
        Glide.with(mActivity).load(doctor.getAvatar()).into(profileImage);
        quiz.setVisibility(View.VISIBLE);
        quiz.setText("向"+doctor.getName()+"医生提问");
        members_number.setText(Html.fromHtml("以服务人数：<font color='#FF0000'>"+doctor.getServed()+"</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务满意度：<font color='#FF0000'>"+doctor.getCompre()+"%</font>"));

        if (doctor.getIs_follow() == 0){

            focus_on.setText("关注他");

        }else{

            focus_on.setText("取消关注");

        }


    }


    private Dialog modify_dialogs;//弹出框

    public void pop_up() {

        View view;//选择性别的view
        RelativeLayout graphic, call_physician, special_video;

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.wenzhen, null);
        TextView members_number = view.findViewById(R.id.members_number);
        members_number.setText("￥" + doctor.getImgtextfee());
        TextView call = view.findViewById(R.id.call);
        call.setText("￥" + doctor.getCallfee());
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        graphic = view.findViewById(R.id.graphic);
        graphic.setOnClickListener(v -> {

            asktype = 1;
            Intent intent = new Intent(mActivity, GraphicVisitsActivity.class);
            intent.putExtra("doctor", doctor);
            intent.putExtra("asktype", asktype + "");
            intent.putExtra("class_id", class_id + "");
            startActivity(intent);
            modify_dialogs.dismiss();

        });

        call_physician = view.findViewById(R.id.call_physician);
        call_physician.setOnClickListener(v -> {

            asktype = 2;
            Intent intent = new Intent(mActivity, GraphicVisitsActivity.class);
            intent.putExtra("doctor", doctor);
            intent.putExtra("asktype", asktype + "");
            intent.putExtra("class_id", class_id + "");
            startActivity(intent);
            modify_dialogs.dismiss();

        });

        special_video = view.findViewById(R.id.special_video);
        special_video.setOnClickListener(v -> {

            asktype = 3;
            Intent intent = new Intent(mActivity, GraphicVisitsActivity.class);
            intent.putExtra("doctor", doctor);
            intent.putExtra("asktype", asktype + "");
            intent.putExtra("class_id", class_id + "");
            startActivity(intent);
            modify_dialogs.dismiss();

        });

    }

    public void getDoctor() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("cmd", "");
        params.put("data[doctor_member_id]", did);
        params.put("data[class_id]", class_id);
        params.put("data[hosp_id]", hosp_id);
        params.put("data[member_id]", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.index/getDoctor", params, handler, 1, 404);

    }

    /**
     * 获取某个科室下的所有医生
     */
    public void getComment() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("cmd", "");
        params.put("data[doctor_member_id]", did);
        params.put("data[row]", 1 + "");
        params.put("data[number]", 10 + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.doctor/getComment", params, handler, 2, 404);

    }

    public void setFollow(){

        List<String> l = new ArrayList<>();
        l.add(did);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setFollow");
        params.put("data[doctor_member_id]", did);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 3, 404);

    }

    @OnClick({R.id.quiz,R.id.focus_on,R.id.more,R.id.my_team})
    public void onViewClicked(View view) {

        Bundle bundle = new Bundle();
        switch (view.getId()) {

            case R.id.quiz:
                pop_up();
                break;

            case R.id.focus_on:
                setFollow();
                break;

            case R.id.more:

                bundle.putString("did",did);
                startActivity(CommentsListActivity.class,bundle);
                break;

            case R.id.my_team:
                bundle.putString("did",did);
                bundle.putSerializable("doctor", doctor);
                bundle.putString("name",doctor.getName());
                bundle.putString("title",doctor.getTitle_name());
                bundle.putString("class_name",doctor.getClass_name()+" "+doctor.getHosp_name());
                bundle.putString("head",doctor.getAvatar());
                startActivity(ExpertTeamActivity.class,bundle);
                break;

        }
    }

}
